package car_video

import (
	"fmt"
	"mime/multipart"

	"io"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var Car_video_chan=make(chan *multipart.FileHeader,1000)

var car_vido_websocket_map = sync.Map{}

func Car_video_upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	Car_video_chan <- file
	c.String(200, "upload success")
}

func Car_video_get(c *gin.Context) {
	upgrader:=websocket.Upgrader{
		ReadBufferSize:  1024*512,
		WriteBufferSize: 1024*512,
	}
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println("Upgrade failed:", err)
		return
	}
	car_vido_websocket_map.Store(ws, struct{}{})
}

func Car_video_sender() {
	for {
		file := <-Car_video_chan
		files,_:=file.Open()
		fileBytes,_:=io.ReadAll(files)
		car_vido_websocket_map.Range(func(key, value interface{}) bool {
			ws := key.(*websocket.Conn)
			ws.WriteMessage(websocket.BinaryMessage, fileBytes)
			return true
		})
		files.Close()
	}
}